package com.mtgdeckbuilder.client.builder;

import static com.mtgdeckbuilder.shared.WizardGathererSiteUtil.getImageUrl;

import java.io.IOException;
import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.mtgdeckbuilder.client.CardService;
import com.mtgdeckbuilder.client.CardServiceAsync;
import com.mtgdeckbuilder.shared.dto.CardDTO;

/**
 * The builder of the card panel
 * 
 * @author Nicolas Deslandes
 */
public class CardPanelBuilder extends PanelBuilder {

   private final CardServiceAsync cardService = GWT.create(CardService.class);

   @Override
   public Panel build() {
      final Button searchButton = new Button("Search");
      final TextBox searchField = new TextBox();
      searchField.addStyleName("searchField");
      searchButton.addStyleName("button");

      final VerticalPanel cardPanel = new VerticalPanel();
      final VerticalPanel resultTable = new VerticalPanel();
      final HorizontalPanel searchPanel = new HorizontalPanel();
      cardPanel.add(searchPanel);
      searchPanel.add(searchField);
      searchPanel.add(searchButton);
      cardPanel.add(resultTable);
      resultTable.setWidth("100%");

      // Focus the cursor on the name field when the app loads
      searchField.setFocus(true);
      searchField.selectAll();

      // Create a handler for the sendButton and nameField
      class SearchHandler implements ClickHandler, KeyUpHandler {
         /**
          * Fired when the user clicks on the sendButton.
          */
         @Override
         public void onClick(final ClickEvent event) {
            sendNameToServer();
         }

         /**
          * Fired when the user types in the nameField.
          */
         @Override
         public void onKeyUp(final KeyUpEvent event) {
            if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
               sendNameToServer();
            }
         }

         /**
          * Send the name from the nameField to the server and wait for a response.
          * 
          * @throws IOException
          */
         private void sendNameToServer() {

            resultTable.clear();
            final String textToServer = searchField.getText();
            final CardDTO args = new CardDTO();
            args.setName(textToServer);
            // Then, we send the input to the server.
            cardService.queryDatabase(args, 0, new AsyncCallback<List<CardDTO>>() {
               @Override
               public void onFailure(final Throwable caught) {
                  resultTable.add(new HTML(caught.toString()));
               }

               @Override
               public void onSuccess(final List<CardDTO> cards) {
                  for (final CardDTO card : cards) {
                     final HorizontalPanel result = new HorizontalPanel();
                     result.setWidth("100%");
                     resultTable.add(result);

                     final Image image = new Image();
                     image.setUrl(getImageUrl + card.getMultiverseId());
                     image.setTitle(card.getMultiverseId() + "");
                     result.add(image);

                     final FlexTable cardDescription = new FlexTable();
                     result.add(cardDescription);

                     cardDescription.setText(1, 1, "Name :");
                     cardDescription.setText(1, 2, card.getName());

                     cardDescription.setText(2, 1, "Cost :");
                     cardDescription.setText(2, 2, card.getCost());

                     cardDescription.setText(3, 1, "Type :");
                     cardDescription.setText(3, 2, card.getType());

                     cardDescription.setText(4, 1, "Text :");
                     cardDescription.setText(4, 2, card.getText());

                     cardDescription.setText(5, 1, "Editions :");
                     final HorizontalPanel editions = new HorizontalPanel();
                     cardDescription.setWidget(5, 2, editions);
                     final Image currentEdition = new Image();
                     currentEdition.setUrl(card.getEdition());
                     editions.add(currentEdition);
                     for (final String urlEdition : card.getOtherEditions()) {
                        final Image edition = new Image();
                        edition.setUrl(urlEdition);
                        editions.add(edition);
                     }

                     cardDescription.setText(6, 1, "Artist :");
                     cardDescription.setText(6, 2, card.getArtist());
                  }

                  resultTable.setVisible(true);
               }
            });
         }
      }

      // Add a handler to send the name to the server
      final SearchHandler handler = new SearchHandler();
      searchButton.addClickHandler(handler);
      searchField.addKeyUpHandler(handler);

      return cardPanel;
   }

}
